

//
//  InvestmentViewController.m
//  DaDaBao
//
//  Created by admin on 15/8/20.
//  Copyright (c) 2015年 User. All rights reserved.
//

#import "InvestmentViewController.h"
#import "InvestmentModel.h"
#import "SuccessViewController.h"
#import "PayPwdViewController.h"


@interface InvestmentViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
@property(nonatomic,strong)UITableView *investTable;
@property(nonatomic,strong)NSMutableArray *titleArr;
@property(nonatomic,strong)UILabel *payLab;
@property(nonatomic,strong)UILabel *cautionLab;
@property(nonatomic,copy)NSString *follow;
@property(nonatomic,strong)NSString *productId;
@property(nonatomic,copy)NSString *total;//可投金额
@property (nonatomic, copy)NSString *modelTotal;
@property(nonatomic,copy)NSString *start;//起投金额
@property(nonatomic,copy)NSString *avalible;//可用余额
@property(nonatomic,assign)float cast;//本次花费
@property (nonatomic, copy) NSString *modelAvalible;  //格式化
@property(nonatomic,strong)UIButton *investBtn;//投资按钮
@property (nonatomic,strong)UIButton * veriyBtn;//验证按钮
@property (nonatomic,copy)NSString * memberNoString;//工号

@end

@implementation InvestmentViewController

- (id)initWithProductId:(NSString *)productId
{
    self = [super init];
    if(self)
    {
        _productId = productId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
    if (!_titleArr) {
        _titleArr = [NSMutableArray arrayWithArray:@[@[@"该项目可投金额(元)",@"可用余额(元)",@"投资金额"],@[@"推荐人工号"]]];
        
    }
   
    [self createUI];
    [self requestData];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:TRUE];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloginView) name:@"reLogin" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

-(void)reloginView
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"登录失败，请重新登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert setTag:101];
    [alert show];
}

-(void)requestData
{
    _total = @"0";
    _modelAvalible = @"0";
    _modelTotal = @"0";
    
    NSDictionary *dict = @{ @"productId":_productId, @"token":[[NSUserDefaults standardUserDefaults]objectForKey:@"token"] };
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
    
    [AppGlobalClass PostDataWithNSstring:INVESTMENT_AMOUNT_URL withDictionary:dict success:^(NSDictionary *dictionary){
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            InvestmentModel *investmentModel = [[InvestmentModel alloc]initWithDictionary:[[[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"] firstObject]];
            _follow = investmentModel.stepMoney;
            _total = investmentModel.leftCredit;
            _modelTotal = investmentModel.leftCreditF;
            _avalible = investmentModel.accountBalance;
            _start = investmentModel.inceptMoney;
            _modelAvalible = investmentModel.accountBalanceF;
            [_investTable reloadData];
        }
        else
        {
            ALERT_VIEW([dictionary objectForKey:@"message"]);
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    } failure:^(NSError *error){
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    } networkerror:^(NSString *networkerror){
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    }];

}
//UI布局
-(void)createUI
{
    TopView *topView =[[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"投资金额"];
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0.0f, 20.0f, 64.0f, 44.0f)];
    
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(buttonBackTapped:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backBtn];
    [self.view addSubview:topView];
//  建表
    if (!_investTable) {
        _investTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, topView.frame.origin.y+topView.frame.size.height, SCREEN_WIDTH,226.0f) style:UITableViewStyleGrouped];
        _investTable.separatorColor = UITableViewCellSelectionStyleNone;
        _investTable.delegate = self;
        _investTable.dataSource = self;
        _investTable.bounces = FALSE;
        _investTable.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
        [self.view addSubview:_investTable];
    }
    
    if (!_cautionLab) {
        _cautionLab = [[UILabel alloc] initWithFrame:CGRectMake(10.0f , _investTable.frame.origin.y+_investTable.frame.size.height + 10, SCREEN_WIDTH - 20.0f, 20.0f)];
        _cautionLab.textAlignment = NSTextAlignmentLeft;
        _cautionLab.textColor = RGBA(246, 84, 3, 1);
        [self.view addSubview:_cautionLab];
        
    }

    if (!_payLab) {
        _payLab = [[UILabel alloc] initWithFrame:CGRectMake(10.0f , _cautionLab.frame.origin.y+_cautionLab.frame.size.height+20.0f, SCREEN_WIDTH - 20.0f, 20.0f)];
        _payLab.textAlignment = NSTextAlignmentRight;
        _payLab.text = @"本次共需支付      元";
        [self.view addSubview:_payLab];

    }
    
//    完成按钮
    if (!_investBtn) {
        _investBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _investBtn.frame = CGRectMake(0.0f, SCREEN_HEIGHT-50.0f, SCREEN_WIDTH, 50.0f);
        [_investBtn addTarget:self action:@selector(buttonInvestTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_investBtn setTitle:@"确认支付" forState:UIControlStateNormal];
        _investBtn.enabled = FALSE;
        _investBtn.backgroundColor = [UIColor grayColor];
        [_investBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.view addSubview:_investBtn];

    }
    
}
#pragma mark- tableViewDatasource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        UILabel *sepLab = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 43.5f, SCREEN_WIDTH, 0.5f)];
        sepLab.backgroundColor = [UIColor lightGrayColor];
        [cell addSubview:sepLab];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.text = self.titleArr[indexPath.section][indexPath.row];
    if (indexPath.section==0) {
        cell.textLabel.textColor = [UIColor grayColor];
        if (indexPath.row==0) {
            UILabel *detailLab = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 150.0f, 10.0f, 140.0f, 24.0f)];
            detailLab.backgroundColor = [UIColor whiteColor];
            detailLab.text = [NSString stringWithFormat:@"%@",_modelTotal];
            detailLab.textAlignment = NSTextAlignmentRight;
            [cell addSubview:detailLab];
        }
        if(indexPath.row == 1)
        {
            UILabel *detailLab = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 150.0f, 10.0f, 140.0f, 24.0f)];
            detailLab.backgroundColor = [UIColor whiteColor];
            detailLab.text = [NSString stringWithFormat:@"%@",_modelAvalible];
            detailLab.textAlignment = NSTextAlignmentRight;
            [cell addSubview:detailLab];
        }if(indexPath.row == 2)
        {
            cell.textLabel.textColor = [UIColor blackColor];
            UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(120.0f, 10.0f, SCREEN_WIDTH - 160.0f, 24.0f)];
            text.backgroundColor = [UIColor whiteColor];
            text.textAlignment = NSTextAlignmentRight;
            text.placeholder = @"必填";
            text.keyboardType = UIKeyboardTypeDecimalPad;
            [text addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
            [cell addSubview:text];
            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-34.0f, 10.0f, 24.0f, 24.0f)];
            lab.text =@"元";
            [cell addSubview:lab];
        }
        
    }
    if (indexPath.section==1) {
        NSString * str = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"memberType"]];
        if ([str isEqualToString:@"1"])
        {
            //代表是内部员工
            cell.textLabel.text = @"员工／经理工号";
            
            UILabel * memberNoLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 200, 0, 190, 44)];
            memberNoLabel.text = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"memberNo"]];
            memberNoLabel.textAlignment = NSTextAlignmentRight;
            [cell addSubview:memberNoLabel];
        }else
        {//外部员工
        UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(120.0f, 10.0f, SCREEN_WIDTH - 220.0f, 24.0f)];
        text.backgroundColor = [UIColor whiteColor];
        text.textAlignment = NSTextAlignmentRight;
        text.placeholder = @"非必填";
        text.keyboardType = UIKeyboardTypeDecimalPad;
        [text addTarget:self action:@selector(MemberNoTextChange:) forControlEvents:UIControlEventEditingChanged];
        
        [cell addSubview:text];
        
        _veriyBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 90, 4, 80, 36)];
        _veriyBtn.backgroundColor = [UIColor grayColor];
        [_veriyBtn setTitle:@"验证" forState:UIControlStateNormal];
        _veriyBtn.layer.cornerRadius = 5;
        _veriyBtn.layer.masksToBounds = TRUE;
        _veriyBtn.enabled = FALSE;
        [_veriyBtn addTarget:self action:@selector(buttonVeriyTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_veriyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [cell addSubview:_veriyBtn];
        }

    }
       return cell;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.titleArr objectAtIndex:section] count];
}
#pragma mark- tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.titleArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 20.0f;
    }
    return 30.0f;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 0.01f;
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1)
    {
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH-20, 30)];
        label.textAlignment = NSTextAlignmentRight;
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor hexStringToColor:RED_COLOR_VALUE];
        
        NSString * str = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"memberType"]];
        if ([str isEqualToString:@"1"])
        {
            label.text = @"＊内部员工投资";
        }else
        {
            label.text = @"*工号输入错误或未填写不计入业绩";
        }
        
        [view addSubview:label];
        return view;
    }
    return nil;
}
//判断整数倍
-(BOOL)judgeStr:(NSString *)str1 with:(NSString *)str2

{
    
    int a=[str1 intValue];
    double b = [str1 doubleValue];
    double s1=[str2 doubleValue];
    int s2=[str2 intValue];
    
    if (a>=1) {
        
        if (s1/b-s2/a==0) {
            
            return TRUE;
            
        }
        
        return FALSE;

    }
    else if(a==0)
    {
        return TRUE;
    }
    else
    {
        double s3 = s1/b;
        NSString *str = [NSString stringWithFormat:@"%f",s3];
        int c = [str intValue];
        if (s3/c == 1)
        {
            return TRUE;
        }
        else
        {
            return FALSE;
        }

    }
}
#pragma mark--投资方法
- (void)buttonInvestTapped:(id)sender
{
    NSString * str = [[NSUserDefaults standardUserDefaults] objectForKey:@"payPasswordVStatus"];
    
    if ([str intValue] == 0)
    {
        ALERT_VIEW(@"请先设置支付密码");
        PayPwdViewController *vc = [[PayPwdViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        if (_cast > [_avalible floatValue])
        {
    
        ALERT_VIEW(@"余额不足,请先充值");
        }
        else
        {
        UIAlertView *inputPwdAlt = [[UIAlertView alloc] initWithTitle:nil message:@"请输入支付密码" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            inputPwdAlt.tag = 100;
        inputPwdAlt.alertViewStyle = UIAlertViewStyleSecureTextInput;
        [inputPwdAlt show];
        }
   
    }
}
#pragma mark-alertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 100)
    {
        switch (buttonIndex)
        {
            case 0:
            {
                
            }
                break;
            case 1:
            {
                
                [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
                //            发送请求
                UITextField *textField = [alertView textFieldAtIndex:0];
                NSDictionary  *dict = nil;
                if (_memberNoString)
                {
                   dict  = @{@"token":[[NSUserDefaults standardUserDefaults] objectForKey:@"token"],@"productId":_productId,@"money":[NSString stringWithFormat:@"%f",_cast],@"payPassword":textField.text,@"memberNo":_memberNoString};
                }else
                {
                    dict = @{@"token":[[NSUserDefaults standardUserDefaults] objectForKey:@"token"],@"productId":_productId,@"money":[NSString stringWithFormat:@"%f",_cast],@"payPassword":textField.text};
                }
                NSLog(@"=====%@",_memberNoString);
                [AppGlobalClass PostDataWithNSstring:PROJECT_BUY_URL withDictionary:dict success:^(NSDictionary *dictionary)
                 {
                     if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
                     {
                         SuccessViewController *successVC = [[SuccessViewController alloc] initWithTitle:@"投资成功" andTips:@"恭喜您，投资成功"];
                         [self.navigationController pushViewController:successVC animated:TRUE];
                         
                     }
                     else{
                         ALERT_VIEW([dictionary objectForKey:@"message"]);
                     }
                     [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
                     
                 }
                                             failure:^(NSError *error)
                 {
                     [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
                     
                 }
                                        networkerror:^(NSString *networkerror)
                 {
                     [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
                     
                 }];
                
            }
                break;
                
            default:
                break;
        }

    }
    else
    {
        [AppGlobalClass exitLogin];
        LoginViewController *loginViewCon = [[LoginViewController alloc]init];
        [self presentViewController:loginViewCon animated:TRUE completion:^{}];
        
        NSArray *listArray = self.navigationController.viewControllers;
        
        id tabBar = [listArray objectAtIndex:1];
        if([[tabBar class] isSubclassOfClass:[UITabBarController class]])
        {
            UITabBarController *tabBarCon = tabBar;
            tabBarCon.selectedIndex = 0;
            [self.navigationController popToViewController:[listArray objectAtIndex:1] animated:TRUE];
        }
        else
        {
            UITabBarController *tabBarCon = [listArray objectAtIndex:2];
            tabBarCon.selectedIndex = 0;
            [self.navigationController popToViewController:[listArray objectAtIndex:2] animated:TRUE];
        }
    }
}
-(void)MemberNoTextChange:(UITextField *)textField
{
    NSString * string = textField.text;
    if (string.length > 11)
    {
        textField.text = [string substringToIndex:11];
    }
    if (string.length >0)
    {
        _veriyBtn.enabled = TRUE;
        _veriyBtn.backgroundColor = [UIColor hexStringToColor:RED_COLOR_VALUE];
    }else
    {
        _veriyBtn.enabled = FALSE;
        _veriyBtn.backgroundColor = [UIColor grayColor];
    }
    _memberNoString = textField.text;
}
#pragma mark-代理
-(void)textChange:(UITextField *)textField
{
    NSString *string = textField.text;
    if (string.length > 20)
    {
        textField.text = [string substringToIndex:20];
        string = textField.text;
    }
    double money = [string doubleValue];
    _cast = money;
    _payLab.text = @"本次共需支付      元";
    
    if (money >= [_start floatValue])
    {
        float a = [_start floatValue];
        float b = [string floatValue];
        float c = b-a;
        NSString *text = [NSString stringWithFormat:@"%f",c];
        BOOL isMultiple = [self judgeStr:_follow with:text];
        
        if (isMultiple == FALSE)
        {
            _investBtn.enabled = FALSE;
            _investBtn.backgroundColor = [UIColor grayColor];
            
            _cautionLab.text = [NSString stringWithFormat:@"增投金额必须是%.2f的整数倍",[_follow doubleValue]];
        }
        else
        {
            
            if (money > [_total floatValue])
            {
                _investBtn.enabled = FALSE;
                _investBtn.backgroundColor = [UIColor grayColor];
                
                _cautionLab.text = @"不能大于可投金额";
            }
            
            else
            {
                _investBtn.enabled = TRUE;
                _investBtn.backgroundColor = [UIColor hexStringToColor:RED_COLOR_VALUE];
                _cautionLab.text = nil;
                NSString*string = [NSString stringWithFormat:@"本次共需支付 %.2f元",money];
                NSRange range = [string rangeOfString: [NSString stringWithFormat:@"%.2f",money]];
                NSMutableAttributedString*attribute = [[NSMutableAttributedString alloc] initWithString: string];
                [attribute addAttributes: @{NSForegroundColorAttributeName: RGBA(246, 84, 3, 1)}range: range];
                [_payLab setText: string];
                [_payLab setAttributedText: attribute];
            }
            
        }
        
    }
    else
    {
        _investBtn.enabled = FALSE;
        _investBtn.backgroundColor = [UIColor grayColor];
        _cautionLab.text = [NSString stringWithFormat:@"不能小于起投金额%.2f",[_start floatValue]];
    }

}

#pragma mark-返回方法
-(void)buttonBackTapped:(id)sender
{
    [self.navigationController popViewControllerAnimated:TRUE];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:TRUE];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark-------------验证工号
-(void)buttonVeriyTapped:(id)sender
{
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];

    [AppGlobalClass PostDataWithNSstring:GETNCMESSAGE withDictionary:@{@"token":[[NSUserDefaults standardUserDefaults]objectForKey:@"token"],@"memberNo":_memberNoString} success:^(NSDictionary *dictionary) {
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            NSDictionary * dict = [[[[dictionary objectForKey:@"responseData"]firstObject]objectForKey:@"rows"]firstObject];
            NSString * name = [NSString stringWithFormat:@"该工号的员工姓名为：%@",[dict objectForKey:@"name"]];
            ALERT_VIEW(name);
        }else
        {
            ALERT_VIEW(@"该工号未同步或工号错误");
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

    } networkerror:^(NSString *networkerror) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

    }];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
